"use client";
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { useTranslations } from 'next-intl';
import { useRouter, useParams } from 'next/navigation';
import { Filter, Search, FileText, Clock, Copy, Trash2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import dayjs from 'dayjs';
import { getProjectsByTeamId, Project, deleteProject } from '@/controller/project';
import { getUserTeam } from '@/controller/team_members';
import { getUser } from '@/controller/auth';
import { toast } from "sonner";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';

export default function ProjectList() {
    const [searchTerm, setSearchTerm] = useState('');
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [projectToDelete, setProjectToDelete] = useState<string | null>(null);
    const t = useTranslations('project');
    const router = useRouter();
    const params = useParams();
    const locale = params.locale as string;
    const [isLoadingProjects, setIsLoadingProjects] = useState(true);
    const [projects, setProjects] = useState<Project[]>([]);
    const fetchProjects = async () => {
        try {
            const user = await getUser();
            if (!user) {
                toast.error('User not found');
                return
            }
            const { data: teams, error } = await getUserTeam(user.id);
            if (!teams || error) {
                console.log('Failed to fetch teams:', error);
                setIsLoadingProjects(false);
                return
            }
            const { data, error: projectError } = await getProjectsByTeamId(teams.team_id);
            if (!data || projectError) {
                toast.error('Failed to fetch projects:', {
                    description: projectError?.message
                });
                return
            } else {
                setProjects(data);
            }
        } catch (error) {
            console.error('Failed to fetch projects:', error);
            toast.error('Failed to fetch projects');
        } finally {
            setIsLoadingProjects(false);
        }
    };
    // 复制功能
    const handleCopy = (id: string) => {
        const projectData = projects.find(project => project.project_id === id);
        if (projectData) {
            navigator.clipboard.writeText(projectData.name);
            toast.success('Copied to clipboard');
        }
    };
    // 打开删除对话框
    const openDeleteDialog = (id: string) => {
        setProjectToDelete(id);
        setDeleteDialogOpen(true);
    };
    // 删除表格功能
    const handleDeleteConfirm = async () => {
        if (!projectToDelete) return;
        try {
            const { error } = await deleteProject(projectToDelete);
            if (error) {
                console.error('删除表格失败:', error);
                return;
            }

            // 删除成功，重新获取表格数据
            fetchProjects();
        } catch (error) {
            console.error('删除表格时发生错误:', error);
        } finally {
            setDeleteDialogOpen(false);
            setProjectToDelete(null);
        }
    };

    // 跳转到项目详情页
    const handleProjectClick = (projectId: string) => {
        router.push(`/${locale}/project/${projectId}`);
    };
    useEffect(() => {
        fetchProjects();
    }, []);
    return (
        <div>
            <Card>
                <CardHeader>
                    <CardTitle>{t('searchFilter')}</CardTitle>
                </CardHeader>
                <CardContent>
                    <div className="flex items-center space-x-2">
                        <div className="relative flex-1">
                            <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                            <Input
                                placeholder={t('searchPlaceholder')}
                                className="pl-9"
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                            />
                        </div>
                        <Button variant="outline">
                            <Filter className="mr-2 h-4 w-4" /> {t('filter')}
                        </Button>
                    </div>
                </CardContent>
            </Card>
            <div className="flex flex-col space-y-4 pt-4">
                {isLoadingProjects ? (
                    <div className="flex items-center justify-center py-16">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
                        <span className="ml-2 text-muted-foreground">加载中...</span>
                    </div>
                ) : projects.length > 0 ? (
                    projects.map((project) => (
                        <Card key={project.project_id} className="overflow-hidden hover:shadow-md transition-shadow duration-300 w-full cursor-pointer" onClick={() => handleProjectClick(project.project_id)}>
                            <CardHeader>
                                <CardTitle className="text-lg font-semibold line-clamp-2">{project.name}</CardTitle>
                            </CardHeader>

                            <CardContent className="pt-0 space-y-4">
                                <div className="flex items-center justify-between">
                                    <div className="flex items-center">
                                        <FileText className="mr-2 h-4 w-4 text-muted-foreground" />
                                        <span className="text-sm">
                                            <Badge variant="outline" className="bg-blue-50 text-blue-700">
                                                {project.search_objective}
                                            </Badge>
                                        </span>
                                    </div>

                                    <div className="flex items-center">
                                        <Clock className="mr-2 h-4 w-4 text-muted-foreground" />
                                        <span className="text-sm text-muted-foreground">
                                            {dayjs(project.create_time).format('YYYY-MM-DD HH:mm')}
                                        </span>
                                    </div>
                                </div>

                                {project.search_keywords && project.search_keywords.length > 0 && (
                                    <div className="mt-2">
                                        <div className="text-sm font-medium text-gray-700 mb-1">关键词：</div>
                                        <div className="flex flex-wrap gap-1">
                                            {project.search_keywords.map((keyword, index) => (
                                                <Badge key={index} variant="outline" className="bg-blue-50 text-blue-700">
                                                    {keyword}
                                                </Badge>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                {project.matching_rules && project.matching_rules.length > 0 && (
                                    <div className="mt-2">
                                        <div className="text-sm font-medium text-gray-700 mb-1">匹配规则：</div>
                                        <div className="flex flex-wrap gap-1">
                                            {project.matching_rules.map((rule, index) => (
                                                <Badge key={index} variant="outline" className="bg-green-50 text-green-700">
                                                    {rule}
                                                </Badge>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                <div className="flex items-center justify-between mt-3">
                                    <div className="flex items-center gap-2">
                                        <Badge variant="outline" className="bg-purple-50 text-purple-700">
                                            keyword: {project.search_keywords?.length}
                                        </Badge>
                                        <Badge variant="outline" className="bg-green-50 text-green-700">
                                            rule: {project.matching_rules?.length}
                                        </Badge>
                                    </div>

                                    <div className="flex items-center space-x-2">
                                        <Button variant="ghost" size="icon" onClick={(e) => {
                                            e.stopPropagation();
                                            handleCopy(project.project_id);
                                        }} title={t('copyProjectName')} className="h-8 w-8 p-0">
                                            <Copy className="h-4 w-4" />
                                        </Button>

                                        <Button variant="ghost" size="icon" className="text-red-500 hover:text-red-700 hover:bg-red-50 h-8 w-8 p-0" onClick={(e) => {
                                            e.stopPropagation();
                                            openDeleteDialog(project.project_id);
                                        }} title={t('deleteProject')}>
                                            <Trash2 className="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    ))
                ) : (
                    <div className="col-span-3 flex items-center justify-center py-16 text-muted-foreground">
                        {t('noProjectsFound')}
                    </div>
                )}
            </div>
            {/* 删除确认对话框 */}
            <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{t('deleteProject')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {t('confirmDelete')}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
                        <AlertDialogAction onClick={handleDeleteConfirm} className="bg-red-500 hover:bg-red-600">
                            {t('delete')}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}